package practise.alogrithm.hundredInterviewQuestions.secondTime;

import practise.alogrithm.hundredInterviewQuestions.Utils.LinkedListBuilder;
import practise.alogrithm.hundredInterviewQuestions.Utils.ListNode;

/**
 * Created by Richard on 7/26/2014.
 */
public class DeleteNodeFromLinkedList {
    public void delete(ListNode listNode,ListNode tobeDelete){
        if(tobeDelete.getNext()!=null) {
            ListNode deleteNext = tobeDelete.getNext();
            tobeDelete.setValue(deleteNext.getValue());
            tobeDelete.setNext(deleteNext.getNext());
            deleteNext.setNext(null);
        }
        else{
            ListNode listNode1 = listNode;
            for(; listNode1.getNext().getValue()!=tobeDelete.getValue();listNode1=listNode1.getNext());
            listNode1.setNext(null);
        }

    }

    public static void main(String[] args){
        ListNode listNode = LinkedListBuilder.buildLinkedListFromArray(new int[]{1,2,3,4,5,6,7});
        DeleteNodeFromLinkedList deleteNodeFromLinkedList = new DeleteNodeFromLinkedList();
        deleteNodeFromLinkedList.delete(listNode,listNode);
        ListNode listNode2 = listNode;
        while(listNode2!=null){
            System.out.print(listNode2.getValue()+"==>");
            listNode2 = listNode2.getNext();
        }
        ListNode listNode1 = new ListNode();
        listNode1.setValue(7);
        deleteNodeFromLinkedList.delete(listNode,listNode1);
        while(listNode!=null){
            System.out.print(listNode.getValue()+"==>");
            listNode = listNode.getNext();
        }
    }
}
